package org.hot100_3;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class leetcode56 {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, (array1, array2) -> array1[0] - array2[0]);
        List<int[]> list = new ArrayList<>();
        int n = intervals.length;

        int left = intervals[0][0];
        int right = intervals[0][1];
        for (int i = 1; i < n; i++) {
            if (intervals[i][0] <= right) {
                right = Math.max(right, intervals[i][1]);
            } else {
                int[] temp = {left, right};
                list.add(temp);

                left = intervals[i][0];
                right = intervals[i][1];
            }
        }
        int[] temp = {left, right};
        list.add(temp);

        int[][] res = new int[list.size()][2];

        for (int i = 0; i < list.size(); i++) {
            res[i] = list.get(i);
        }

        return res;
    }
}
